package C2DMRelated;

import Database.Database;
import TomcatRelated.ServerClientCodes;
import TomcatRelated.TomcatProtocolImp;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;
import androidApplication.javaFiles.MainActivity;

public class RegistrationHandler
{

	//***************************************Class Variables*******************************************//


	private final String tag = new String("RegistrationHandler");


	//***************************************Constructors*******************************************//


	public RegistrationHandler()
	{
	}


	//***************************************Public Methods*******************************************//


	public void registerToC2DM(Context context)
	{
		//Sending to Google's cloud a request for a c2dm registration_id
		Intent registrationIntent = new Intent("com.google.android.c2dm.intent.REGISTER");
		String emailOfSender = new String("reuvenlevitsky@gmail.com");//the account authorized to send messages to the application, typically the email address of an account set up by the application's developer.  

		//parameters that needed to be sent to Google's cloud
		registrationIntent.putExtra("app", PendingIntent.getBroadcast(context, 0, new Intent(), 0)); // boilerplate
		registrationIntent.putExtra("sender", emailOfSender);

		context.startService(registrationIntent);
	}


	public void handleRegistration(final Context context, final Intent intent) 
	{	
		Log.v(tag ,"handling registration.........");

		final String registration = intent.getStringExtra("registration_id");

		if (intent.getStringExtra("error") != null) 
		{
			Log.d("c2dm", "registration failed");
			String error = intent.getStringExtra("error");
			if(error == "SERVICE_NOT_AVAILABLE"){
				Log.d(tag, "SERVICE_NOT_AVAILABLE");
			}else if(error == "ACCOUNT_MISSING"){
				Log.d(tag, "ACCOUNT_MISSING");
			}else if(error == "AUTHENTICATION_FAILED"){
				Log.d(tag, "AUTHENTICATION_FAILED");
			}else if(error == "TOO_MANY_REGISTRATIONS"){
				Log.d(tag, "TOO_MANY_REGISTRATIONS");
			}else if(error == "INVALID_SENDER"){
				Log.d(tag, "INVALID_SENDER");
			}else if(error == "PHONE_REGISTRATION_ERROR"){
				Log.d(tag, "PHONE_REGISTRATION_ERROR");
			}
			else
			{
				Log.v(tag,"An Unknown Error Accured: " + error);
			}

			registerToC2DM(context);
		} 
		else if (intent.getStringExtra("unregistered") != null) 
		{
			// TODO - complete this case! (just wrote something that makes sense)
			String my_android_id = Database.getInstance(context).get_device_id();
			TomcatProtocolImp.getInstance().unregister(my_android_id);
			Log.v(tag,"Unregisteration Accured");
		} 
		else if (registration != null) 
		{
			// Send the registration ID to the 3rd party site that is sending the messages.
			// This should be done in a separate thread.
			// When done, remember that all registration is done.
			Log.v(tag,"\n" + "registrationID is: " + registration + "\n");
			Log.v(tag,"registrationID recieved, sending ID to appServer.........");

			//getting a google account
			String googleAccount = getGoogleAcount(context, intent);
			Database.getInstance(context).set_userProfile_google_account(googleAccount);

			//getting the device's unique id
			String my_android_id = Database.getInstance(context).get_device_id();


			if (googleAccount == null)
			{
				Toast.makeText(context, "This device doesn't have a google account!", Toast.LENGTH_LONG).show();
				Log.v(tag, "This device doesn't have a google account!");
			}
			else if (my_android_id == null)
			{	
				Toast.makeText(context, "This device's android_id is 'null' !", Toast.LENGTH_LONG).show();
				Log.v(tag, "This device's android_id is 'null' !");
			}
			else // Everything is good - we proceed of sending the key to the application server
			{
				//setting the user profile in the database
				Database.getInstance(context).set_userProfile_c2dm_register_id(registration);
				Log.v(tag, "android_id: " + my_android_id + " google_account: " + googleAccount + 
						" c2dm_register_id: " + registration);

				String response = TomcatProtocolImp.getInstance().register(my_android_id, googleAccount, registration);

				if(response == null)
				{
					Log.v(tag, "Response was null!!! the comminucation with server failed!");
				}
				else if(response.equals(ServerClientCodes.C2DMRegistrationKeyReceived))
				{
					Log.v(tag, "Sending intent to MainActivity");
					
					Intent newIntent = new Intent(context, MainActivity.class);
					newIntent.putExtra("finished registration!", "");
					newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					context.startActivity(newIntent);
				}
				else
				{
					Log.v(tag, "Unknown response from server: " + response);
				}

				Log.v(tag,"finished registration to Server");
			}
		}
	}


	//***************************************Private Methods*******************************************//


	/*
	 * this function gets one google account from this device, in the future we can had a mechanism that allows
	 * the user to choose which account he is using, and the current function may stay a DEFAULT
	 */
	private String getGoogleAcount(Context context, Intent intent)
	{
		Account[] listOfAccounts = (AccountManager.get(context).getAccountsByType("com.google"));

		if (listOfAccounts.length == 0)
		{
			return null;
		}
		else
		{
			Account googleAccount = (AccountManager.get(context).getAccountsByType("com.google"))[0];
			return googleAccount.name;
		}
	}


}
